﻿using Model;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace Business
{
    public class SmsBiz
    {
        public int SaveItem(Sms item)
        {
            var dbContext = new Context();

            dbContext.Smss.Add(item);
            dbContext.SaveChanges();

            return item.Id;
        }

        public void UpdateItem(Sms item)
        {
            var dbContext = new Context();
            dbContext.Entry(item).State = EntityState.Modified;
            dbContext.SaveChanges();
        }

        public Sms LoadItem(int id)
        {
            var dbContext = new Context();
            return (from item in dbContext.Smss
                    where item.Id == id
                    select item).First();
        }

        public Sms LoadItem(string key)
        {
            var dbContext = new Context();
            var query = (from item in dbContext.Smss
                    where item.Name == key
                    select item).ToList();

            if(query != null && query.Count > 0)
            {
                return query[0];
            }

            return null;
        }

        public void RemoveItem(List<Sms> items)
        {
            var dbContext = new Context();

            string ids = string.Empty;

            foreach (var item in items)
            {
                ids += item.Id + ",";
            }

            if (ids.EndsWith(","))
            {
                ids = ids.Substring(0, ids.Length-1);

                string deleteCommand = string.Format(Constants.DeleteCommand, "Sms", ids);
                dbContext.Database.ExecuteSqlCommand(deleteCommand);
            }            
        }

        public List<Sms> LoadItems()
        {
            var dbContext = new Context();
            return (from item in dbContext.Smss
                    orderby item.Name
                    select item).ToList();
        }
    }
}
